//
//  MFWSdkEnvironment.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-7-24.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "MFWSdkEnvironment.h"
#import "OpenUDID.h"
#import "UIDevice+Hardware.h"
#import "MULLoginManager.h"
#import <AdSupport/AdSupport.h>

//static NSString *const kKeychain_Service_Token = @"keychain_token";
//static NSString *const kUserDefaults_Str_Token = @"nekot";

@interface MFWSdkEnvironment()
{
    NSString *_pushDeviceToken;
}
@property(nonatomic, strong)id<IMFWShare>mfwShare;
@end

@implementation MFWSdkEnvironment
@synthesize pushDeviceToken = _pushDeviceToken;

+ (MFWSdkEnvironment*)sharedInstance;
{
    static MFWSdkEnvironment *_sharedInstance = nil;
    if (_sharedInstance == nil)
	{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedInstance = [[MFWSdkEnvironment alloc] init];
			
        });
	}
	return _sharedInstance;
}

- (void)fillClientConfig:(MFWClientConfig*)config
{
    self.consumerKey = config.consumerKey;
    self.consumerSecret = config.consumerSecret;
    self.defaultToken = config.defaultToken;
    self.defaultTokenSecret = config.defaultTokenSecret;
    
    self.appId = config.appId;
    self.channelId = config.channelId;
    self.isDEBUG = config.isDEBUG;
    
    self.mfwShare = config.mfwShare;
    
    self.patchingEnabled = config.patchingEnabled;
    
    self.ver = config.ver;
    self.idfa = config.idfa;
}

static NSString *const tokenSecretSplitor = @"|&|";

- (NSString *)tokenSecretSerialStr:(NSString*)secret andToken:(NSString*)token
{
    NSArray *serialArray = @[secret, token];
    return [MFWJsonUtils stringEncodingJsonObject:serialArray];
}

- (void)getToken:(NSString**)token secret:(NSString**)secret fromTokenSecretSerial:(NSString*)serial;
{
    NSArray *serialArray = [MFWJsonUtils parseJsonString:serial];
    if (serialArray && serialArray.count >=2)
    {
        *secret = [serialArray objectAtIndex:0];
        *token = [serialArray objectAtIndex:1];
    }
}


- (BOOL)hasLogin;
{
    return ![MFWStringUtils isEmptyString:_userInfo.uid];

//    return  ![MFWStringUtils isEmptyString:self.accessToken]
//                && ![MFWStringUtils isEmptyString:self.tokenSecret]
//                && ![MFWStringUtils isEmptyString:_userInfo.uid];
}


-(BOOL)setCookie:(NSDictionary*)cookie {
    return [[MULLoginManager sharedInstance]setCookie:cookie];
}


- (void)setPushDeviceToken:(NSString *)pushDeviceToken
{
    _pushDeviceToken = pushDeviceToken;
    [[NSUserDefaults standardUserDefaults] setValue:pushDeviceToken forKey:@"device_token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString*)pushDeviceToken
{
    if ([_pushDeviceToken length] == 0)
    {
        _pushDeviceToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"device_token"];
        if (_pushDeviceToken == nil)
        {
            _pushDeviceToken = @"";
        }
    }
    
    return _pushDeviceToken;
}

- (NSString*)systemUserAgent
{
    if (!_systemUserAgent)
    {
        UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
        NSString* ua = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
        _systemUserAgent  = [ua copy];
    }
    return _systemUserAgent;
}

- (NSString*)mfwUserAgent
{
    if (!_mfwUserAgent)
    {
        _mfwUserAgent = [NSString stringWithFormat:@"yuwei appver/%@  %@", self.appVersion, self.systemUserAgent];
    }
    return _mfwUserAgent;
}

#pragma mark - Initial methods

- (void)_initializeAppInfo;
{
    self.appVersion = [MFWVersionUtils appVersion];
    self.mfwSDKVersion = [MFWSdk sdkVersion];
    
    self.appCode = [[NSBundle mainBundle] bundleIdentifier];
    
#ifdef BETA_TESTING
    self.appCode = @"com.youyuwei";
#endif
}

- (void)_initializeDeviceInfo;
{
    self.openUDID = [OpenUDID value];
    self.hardwareModel = [UIDevice hardwareModel];
    self.systemVersion = [UIDevice currentDevice].systemVersion;
}

- (void)_initializeLoginInfo
{
    //yuweitodo
    MFWUserInfo *userInfo = [MFWUserInfo loadFromDisk];
    
    if (userInfo == nil)
    {
        userInfo = [[MFWUserInfo alloc] init];
    }
    
    _userInfo = userInfo;
    
    //取登陆用户的token 和 tokenSecret
    if (![MFWStringUtils isEmptyString:_userInfo.uid])
    {
        NSError *error = nil;
        NSString *token = nil;
        NSString *tokenSecret = nil;
        
        // 1. 判断UniLoginSDK中是否登录
        if ([MULLoginManager sharedInstance].hasLogin)
        {
            [MULLoginManager getSignatureToken:&token andSecret:&tokenSecret];
            self.accessToken = token;
            self.tokenSecret = tokenSecret;
        }
        else
        {
            // 2. 若没有登录，为了兼容UniLoginSDK之前的版本，则取MFWSdk存到keychain的token，若取到了则设置到UniloginSDK中
            NSString *secretSerial = [STKeychain getPasswordForUsername:_userInfo.uid andServiceName:@"keychain_token" error:&error];
            
            if (secretSerial)
            {
                [self getToken:&token secret:&tokenSecret fromTokenSecretSerial:secretSerial];
                self.accessToken = token;
                self.tokenSecret = tokenSecret;
            }
            
            if (self.accessToken && self.tokenSecret)
            {
                BOOL ret = [[MULLoginManager sharedInstance] updateAccessToken:self.accessToken andSecret:self.tokenSecret forUid:_userInfo.uid];
                if (ret)
                {
                    //删除MFWSdk中的keychain token
                    [STKeychain deleteItemForUsername:_userInfo.uid andServiceName:@"keychain_token" error:nil];
                }
            }
        }
        
    }
    
//    if (!self.accessToken && userInfo)
//    {
//        //没有token(即未登陆）时，但是却有用户信息，正常不会产生这样的情况，若真的发生了，则删掉用户信息，认为没有登陆
//        
//        [_userInfo clear];
//    }
}

#pragma mark -

- (id)init
{
    self = [super init];
    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUserLogout) name:kSDK_Notify_UserWillLogout object:nil];
        
//        [self _initializeAppInfo];
//        [self _initializeDeviceInfo];
        [self _initializeLoginInfo];
    }
    return self;
}

- (void)handleUserLogout
{
//    [STKeychain deleteItemForUsername:_userInfo.uid andServiceName:kKeychain_Service_Token error:nil];
    
    self.accessToken = nil;
    self.tokenSecret = nil;
    
    [[MULLoginManager sharedInstance] logout];
    
    [_userInfo clear];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kSDK_Notify_UserDidLogout object:nil];
}
@end
